package com.opdar.athena.message.agent.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;
import java.util.concurrent.Callable;

/**
 * Created by shiju on 2017/7/2.
 */
public class ClientTask implements Callable<Client> {
    private final InetSocketAddress address;
    private final byte[] project;
    private final int version;
    public ClientTask(InetSocketAddress address, String project, int version) {
        this.address = address;
        this.project = project.getBytes();
        this.version = version;
    }

    @Override
    public Client call() throws Exception {
        NioEventLoopGroup group = new NioEventLoopGroup();
        Bootstrap b = new Bootstrap();
        b.group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline p = ch.pipeline();
                        p.addLast(
                                new ClientDecoder(project),
                                new ClientEncoder(project, version)
                        );
                    }
                });
        Channel channel = b.connect(address.getAddress().getHostAddress(), address.getPort()).sync().channel();
        return new Client(address,group,channel).messageAgentRegist();
    }
}
